import {FC, useState, useEffect} from "react";
import {xhrGet, xhrPostJson} from "@/services/index";
import {toFirstLowerCase} from "@ey-utils/utils";
import { history } from 'umi';
import { message } from 'antd';
interface ApiProps {
    url: string,
    codeKey?: string
    params?: {

    };
}
interface  DynamicLinkProps  {
    value?: any[];
    api?: ApiProps,
    codeKey?: string,
    isInnerLink?: boolean
    linkRecord?: any
}

const DynamicLink:FC<DynamicLinkProps> = (props: any) => {
    const {
        value,
        api,
        isInnerLink = false,
        linkRecord,
        ...others
    } = props;
    const [url, setUrl] = useState('');
    // const [options, setOptions] = useState([]);
    console.log('props', props)
    const { method = 'GET' } = api || {};
    // useEffect(() => {
    //     if(!value) return
    //     if(isInnerLink) {
    //         const { modelCode, pageType, type } = linkRecord || {};
    //         setUrl(`/#/yadea-asm/invoice/${toFirstLowerCase(pageType || modelCode || '')}-invoice/detail?code=${value}&pageType=${pageType}&type=${type}`)
    //     } else {
    //         const xhrMethod = method === 'GET' ? xhrGet : xhrPostJson;
    //         xhrMethod(api?.url || '/asm/asmOa/getOaUrl', {
    //             [api?.codeKey || 'code']: value
    //         }).then(res => {
    //             if(res?.success) {
    //                 setUrl(res?.result)
    //             }
    //         })
    //     }
    //
    // }, [value, linkRecord]);
    const toUrl = () => {
        if(isInnerLink) {
            const { modelCode, pageType, type } = linkRecord || {};
            if (!pageType || !type || !value) {
                message.error('请核对单据类型，单据编码等是否存在');
                return;
            }
            window.open(`/#/yadea-asm/invoice/${toFirstLowerCase(pageType || modelCode || '')}-invoice/detail?code=${value}&pageType=${pageType}&type=${type}` || '', '_blank');
            // setUrl(`/#/yadea-asm/invoice/${toFirstLowerCase(pageType || modelCode || '')}-invoice/detail?code=${value}&pageType=${pageType}&type=${type}`)
        } else {
            const xhrMethod = method === 'GET' ? xhrGet : xhrPostJson;
            xhrMethod(api?.url || '/asm/asmOa/getOaUrl', {
                [api?.codeKey || 'code']: value
            }).then(res => {
                if(res?.success) {
                    // setUrl(res?.result)
                    if (!res?.result) {
                        message.error('没有链接信息');
                        return;
                    }
                    console.log('dynamic-link', res?.result);
                    window.open(res?.result || '', '_blank');
                }
            })
        }
    };
    return (
        <a href="javascript:void(0)" onClick={toUrl}>
            {value}
        </a>
    )
};

export default DynamicLink;
